import React from "react";
import { View, Text } from "@tarojs/components";
import { AtImagePicker, AtDivider, AtTextarea, AtToast } from "taro-ui";
import Taro from "@tarojs/taro";
import "./create.scss";
import { useState } from "react";
import { Input } from "@tarojs/components";
import { addArticle } from "../../../services/api";

const ArticleCreate = (props) => {
  const [uploadFiles, setUploadFiles] = useState([]);
  const [title, setTitle] = useState("");
  const [content, setContent] = useState("");
  const [isOpenToast, setIsOpenToast] = useState(false);
  const [toastText, setToastText] = useState("");

  const validateForm = (data) => {
    const { title, content, uploadFiles } = data;
    if (!title) {
      return "标题不能为空";
    }
    if (!content) {
      return "内容不能为空";
    }
    if (uploadFiles.length == 0) {
      return "文章图片不能为空";
    }
  };

  const handlerImagesChange = (files, operationType, removeIndex) => {
    console.log("change:", files, operationType, index);
    if (operationType == "add") {
      const { file } = files[files.length - 1];
      console.log("change2:", file.path);
      const uploadTask = Taro.uploadFile({
        url: `${process.env.TARO_APP_BASE_URL}/api/articleImgs/uploadImg_url`,
        name: "file",
        filePath: file.path,
        header: {
          Authorization: `Bearer ${Taro.getStorageSync("Authorization")}`,
        },
        success: (result) => {
          console.log("upload:", result);
          const { statusCode, data } = result;
          if (statusCode == 200) {
            const json = JSON.parse(data);
            const { result } = json;
            console.log("result:", result);
            setUploadFiles([...uploadFiles, { url: result.url }]);
          }
        },
      });
      // uploadTask.progress((res) => {
      //   console.log("上传进度", res.progress);
      //   console.log("已经上传的数据长度", res.totalBytesSent);
      //   console.log("预期需要上传的数据总长度", res.totalBytesExpectedToSend);
      // });
    } else {
      const removedFiles = uploadFiles.filter(
        (value, index) => removeIndex != index
      );
      setUploadFiles(removedFiles);
    }
  };

  const handlerClickSubmit = () => {
    const data = {
      title,
      content,
      uploadFiles,
    };
    const msg = validateForm(data);
    if (msg) {
      setToastText(msg);
      setIsOpenToast(true);
    }
    const submitData = {
      title: data.title,
      content: data.content,
      banner_imgs: data.uploadFiles,
    };
    addArticle(submitData).then((res) => {
      console.log("res:", res);
    });
  };

  return (
    <View className="article-create">
      <View className="image-upload">
<AtImagePicker files={uploadFiles} onChange={handlerImagesChange} />
      </View>
      <View className="title">
        <Input
          value={title}
          className="title-input"
          placeholder="填写标题会有更多赞哦"
        />
      </View>
      <View className="content">
        <AtTextarea
          className="content-input"
          placeholder="添加正文"
          placeholderClass="content-placeholder"
          count={false}
        />
      </View>
      <View className="footer">
        <View className="add-btn" onClick={handlerClickSubmit}>
          <Text className="add-btn-text">发布笔记</Text>
        </View>
      </View>
      <AtToast text={toastText} isOpened={isOpenToast} />
    </View>
  );
};

export default ArticleCreate;

definePageConfig({
  navigationBarTitleText: "创建",
});
